package com.szis.auth.oauth2.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.oauth2.config.SaOAuth2ServerConfig;
import cn.dev33.satoken.oauth2.exception.SaOAuth2Exception;
import cn.dev33.satoken.oauth2.strategy.SaOAuth2Strategy;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.szis.auth.oauth2.entity.User;
import com.szis.auth.oauth2.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * oauth2服务的自定义配置
 *
 * @author: yxl
 * 2025-07-16
 */

@Configuration
public class Oauth2ServerConfig {

    @Resource
    private IUserService userService;

    @Autowired
    public void configOAuth2Server(SaOAuth2ServerConfig oauth2Server) {

        // 登录处理
        SaOAuth2Strategy.instance.doLoginHandle = (name, pwd) -> {
            String grantType = SaHolder.getRequest().getParamNotNull("grant_type");
            if("password".equals(grantType)){
                User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, name).eq(User::getPassword, pwd));
                if(user != null){
                    StpUtil.login(user.getBid());
                    return SaResult.ok().set("token", StpUtil.getTokenValue());
                } else {
                    throw new SaOAuth2Exception("无效账号密码");
                }
            }

            throw new SaOAuth2Exception("无效账号密码");
        };

        // 重写 AccessToken 创建策略，返回会话令牌
        SaOAuth2Strategy.instance.createAccessToken = (clientId, loginId, scopes) -> {
            return StpUtil.getOrCreateLoginSession(loginId);
        };

    }


}
